#include "th_iat114_i.h"
#include "ui_th_iat114_i.h"
//#include "convert.h"
#include "curve.h"
#include <QDebug>
#include <QFileInfo>
#include <QSettings>
#include <QMessageBox>
#include <QPainter>
#include <QPainterPath>

TH_IAT114_I::TH_IAT114_I(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TH_IAT114_I)
{
    ui->setupUi(this);
    initialize();
}

void TH_IAT114_I::initialize()
{
    this->setWindowTitle(tr("高压不对称采集模块(TH-IAT114-I)测试工具"));
//    this->setFixedSize(369, 312);
    this->ui->statusBar->showMessage(tr("请连接分机！"));
    this->time.setInterval(2000);

    connect(ui->pushButton, &QPushButton::clicked, this, &TH_IAT114_I::on_pushButton);
    connect(ui->lineEdit_remoteIP, &QLineEdit::editingFinished, this, &TH_IAT114_I::on_remoteIPChanged);
    connect(&this->time, &QTimer::timeout, this, &TH_IAT114_I::on_testTimeout);
    connect(&socket, &QUdpSocket::readyRead, this, &TH_IAT114_I::on_socketReceive);
    connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(on_spinBoxChanged(int)));
    connect(ui->checkBox, &QCheckBox::toggled, this, &TH_IAT114_I::on_AutoTest);
    connect(ui->pushButton_Curve, &QPushButton::clicked, this, &TH_IAT114_I::on_getCurve);

    readConfig();
    loadName();
}

TH_IAT114_I::~TH_IAT114_I()
{
    delete ui;
}

TH_IAT114_I::DataFrame TH_IAT114_I::toDataFrame(QByteArray array)
{
    TH_IAT114_I::DataFrame ret;

    if(array.size() != 12) {
        qDebug() << "高压不对称采集模块数据不完整：" << array.data();
        return ret;
    }

    qint16 *pdata;
    pdata = (qint16 *)array.data();

    ret.voltage1    = (float) * pdata * 0.1;
    ret.voltage2  = (float) * (pdata + 1) * 0.1;
    ret.voltage3  = (float) * (pdata + 2) * 0.1;
    ret.voltage4  = (float) * (pdata + 3) * 0.1;
    ret.period = (float) * (pdata + 4) * 0.1;
    ret.kgl = *(pdata + 5);

    return ret;
}

void TH_IAT114_I::setDisplay(DataFrame data)
{
    ui->lineEdit_1->setText(QString::number(data.voltage1, 'f', 2));
    ui->lineEdit_2->setText(QString::number(data.voltage2, 'f', 2));
    ui->lineEdit_3->setText(QString::number(data.voltage3, 'f', 2));
    ui->lineEdit_4->setText(QString::number(data.voltage4, 'f', 2));
    ui->lineEdit_5->setText(QString::number(data.period, 'f', 2));

    if((bool)(data.kgl & 0x01)) {
        ui->checkBox_kgl->setChecked(true);
        ui->checkBox_kgl->setText(tr("占用"));
    } else {
        ui->checkBox_kgl->setChecked(false);
        ui->checkBox_kgl->setText(tr("空闲"));
    }
}

void TH_IAT114_I::clearDisplay()
{
    ui->spinBox->setRange(0, 0);

    ui->lineEdit_1->clear();
    ui->lineEdit_2->clear();
    ui->lineEdit_3->clear();
    ui->lineEdit_4->clear();
    ui->lineEdit_5->clear();
    ui->checkBox_kgl->setChecked(false);
    ui->checkBox_kgl->setText(tr("空闲"));
}

void TH_IAT114_I::readConfig()
{
    QFileInfo file("./cfg.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("cfg.ini", QSettings::IniFormat);
        ui->lineEdit_remoteIP->setText(read->value("UDP/RemoteIP").toString());
        ui->spinBox_remotePort->setValue(read->value("UDP/RemotePort").toInt());
        bool temp = read->value("UDP/FixedLocalPort").toBool();
        ui->checkBox_localPort->setChecked(temp);
        ui->spinBox_localPort->setValue(read->value("UDP/LocalPort").toInt());

        delete read;
    } else {
        qDebug() << "cfg.ini 文件不存在！";
    }
}

void TH_IAT114_I::writeConfig()
{

    QSettings *writer = new QSettings("cfg.ini", QSettings::IniFormat);
    writer->setValue("UDP/RemoteIP", ui->lineEdit_remoteIP->text());
    writer->setValue("UDP/RemotePort", ui->spinBox_remotePort->value());

    if(ui->checkBox_localPort->isChecked()) {
        writer->setValue("UDP/FixedLocalPort", true);
    } else {
        writer->setValue("UDP/FixedLocalPort", false);
    }

    writer->setValue("UDP/LocalPort", ui->spinBox_localPort->value());

    delete writer;
}

void TH_IAT114_I::on_pushButton()
{
    if(socket.isValid()) {
        ui->checkBox->setChecked(false);
        this->time.stop();
        clearDisplay();
        socket.close();
        ui->groupBox->setEnabled(false);
        ui->lineEdit_remoteIP->setEnabled(true);
        ui->spinBox_remotePort->setEnabled(true);
        ui->checkBox_localPort->setEnabled(true);
        ui->spinBox_localPort->setEnabled(true);
        ui->pushButton->setText(tr("连接分机"));
        ui->statusBar->showMessage(tr("请重新连接分机!"));
    } else {
        if(ui->checkBox_localPort->isChecked()) {
            this->socket.bind(ui->spinBox_localPort->value());
        }

        this->socket.connectToHost(QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());

        if(socket.isValid()) {
            writeConfig();
            ui->groupBox->setEnabled(true);
            ui->lineEdit_remoteIP->setEnabled(false);
            ui->spinBox_remotePort->setEnabled(false);
            ui->checkBox_localPort->setEnabled(false);
            ui->spinBox_localPort->setEnabled(false);
            ui->pushButton->setText(tr("断开连接"));
            ui->statusBar->showMessage(tr("\"回车\"进行1次测试!"));
        }
    }

}

void TH_IAT114_I::on_remoteIPChanged()
{
    QHostAddress ip(ui->lineEdit_remoteIP->text());

    if(ip.toString() != NULL) {
        this->ui->lineEdit_remoteIP->setText(ip.toString());
    } else {
        QMessageBox::warning(this, tr("错误："), tr("输入的分机IP地址有误，请重新输入!"), QMessageBox::Ok);
        ui->lineEdit_remoteIP->setFocus();
    }
}

void TH_IAT114_I::startOneTest()
{
    qDebug() << "开始一次手动测试……";
    this->ui->statusBar->showMessage(tr("正在测试……"));
    char code[2];
    code[0] = 0x01;
    code[1] = 0xC0;
    socket.writeDatagram(code, 2, QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());
    qDebug() << "开起定时器……";
    this->time.start();
}

void TH_IAT114_I::on_testTimeout()
{
    qDebug() << "分机超时未响应……";
    this->time.stop();

    if(ui->spinBox->isEnabled()) {
        this->statusBar()->showMessage(tr("电压测试超时……请确认ip及端口号是否正确,分机是否在正常工作！"));
        this->arrayData.clear();
        ui->spinBox->setRange(0, 0);
        ui->spinBox->setValue(0);

        if(ui->checkBox->isChecked()) {
            startOneTest();
        }
    } else {
        this->statusBar()->showMessage(tr("取曲线超时……请确认ip及端口号是否正确,分机是否在正常工作！"));
        ui->spinBox->setEnabled(true);
        ui->checkBox->setEnabled(true);
    }
}

void TH_IAT114_I::keyPressEvent(QKeyEvent *event)
{
    if(!socket.isValid()) return;

    if(ui->checkBox->isChecked()) return;

    if(time.isActive()) return;

    if(event->key() == Qt::Key_Return) {
        startOneTest();
    }
}

void TH_IAT114_I::on_spinBoxChanged(int arg)
{
    if(this->arrayData.isEmpty()) {
        ui->spinBox->setRange(0, 0);
        clearDisplay();
    } else {
        DataFrame dat = this->toDataFrame((arrayData.mid((arg - 1) * 12, 12)));
        setDisplay(dat);
    }
    setName(arg);
}

void TH_IAT114_I::on_socketReceive()
{
    qDebug() << "收到数据……";
    QByteArray ret;
    ret.resize(socket.pendingDatagramSize());
    QHostAddress ip;
    quint16 port;

    socket.readDatagram(ret.data(), socket.pendingDatagramSize(), &ip, &port);
//    qDebug() << ret;

    if(ret.isEmpty()) return;

    if(ret.at(0) != 0x00) return;

    switch(ret[1]) {
        //高压不对称电压采集
    case(char)0xC0: {
//        quint16 len = (ret[3] << 8) + ret[2];
        quint16 *plen = (quint16*)ret.data();
        quint16 len = *(plen + 1);

        if(len == 0x00) {
            ui->statusBar->showMessage(tr("分机未配置站联电压模块,请检查分机配置！"));
            this->time.stop();
            return;
        }

        if(len * 2 != ret.size() - 4) {
            ui->statusBar->showMessage(tr("非完整的高压不对称数据包……"));
            return;
        }

        this->arrayData = ret.mid(4);
        ui->spinBox->setRange(1, len / 6);
        ui->statusBar->showMessage(tr("测试完成！"));
        DataFrame dat = toDataFrame(arrayData.mid((ui->spinBox->value() - 1) * 12, 12));
        setDisplay(dat);

        if(ui->checkBox->isChecked()) {
            startOneTest();
        } else {
            this->time.stop();
        }

        break;
    }

    case(char)0xC2: {
        quint16 * plen = (quint16 *)ret.mid(3).data();

        if(ret.size() == 5 && *plen == 0 && (int)ret[2] == ui->spinBox->value() - 1) {
            ui->statusBar->showMessage(tr("该引索的高压不对称暂无曲线！"));
            time.stop();
            ui->spinBox->setEnabled(true);
            ui->checkBox->setEnabled(true);
            return;
        }

        if(ret.size() != 405 || ret.size() != (*plen) * 2 + 5) {
            ui->statusBar->showMessage(tr("非完整的高压不对称曲线数据包……"));
            return;
        }

        if((int)ret[2] != ui->spinBox->value() - 1) {
            ui->statusBar->showMessage(tr("收到非当前模块索引的高压不对称曲线！"), 2000);

        } else {
            ui->statusBar->showMessage(tr("取曲线完成！"));

            ui->spinBox->setEnabled(true);
            ui->checkBox->setEnabled(true);
            time.stop();
            Curve curve(ret.mid(5));
            curve.exec();
        }

        break;
    }

    default: {
        ui->statusBar->showMessage(tr("非高压不对称模块的数据包……"));
        break;
    }
    }
}

void TH_IAT114_I::on_AutoTest(bool checked)
{
    if(checked) {
        ui->pushButton_Curve->setEnabled(false);
        startOneTest();
    } else {
        ui->pushButton_Curve->setEnabled(true);
    }
}

void TH_IAT114_I::on_getCurve()
{
    qDebug() << "开始曲线";

//    QByteArray dat = Convert::toByteArray(" 00 C2 04 C8 00 86 00 69 00 86 00 69 00 7D 00 69 00 69 00 56 00 7D 00 4D 00 4D 00 4D 00 4D 00 43 00 30 00 30 00 26 00 26 00 30 00 13 00 09 00 1C 00 13 00 09 00 00 00 1B 07 D4 0A BE 0C 8C 0E 7D 0F 9A 00 E7 00 B3 FF F0 00 AD 00 7D 00 A3 00 69 00 73 00 69 00 69 00 60 00 7D 00 56 00 69 00 60 00 60 00 60 00 39 00 39 00 39 00 4D 00 30 00 1C 00 26 00 26 00 39 00 30 00 26 00 26 00 30 00 13 00 13 00 1C 00 09 00 09 00 13 00 00 00 13 00 13 00 13 00 09 00 00 00 F6 FF 00 00 F6 FF 00 00 09 00 09 00 E3 FF F6 FF F6 FF D9 FF 09 00 EC FF 00 00 EC FF F6 FF 00 00 EC FF EC FF 00 00 F6 FF F6 FF 00 00 EC FF 00 00 EC FF 00 00 E3 FF EC FF EC FF EC FF E3 FF EC FF F6 FF F6 FF EC FF E3 FF F6 FF EC FF F6 FF D9 FF 00 00 D9 FF E3 FF E3 FF E3 FF D9 FF E3 FF D9 FF EC FF E3 FF CF FF EC FF D9 FF CF FF C6 FF D9 FF CF FF E3 FF D9 FF C6 FF CF FF CF FF D9 FF C6 FF E3 FF D9 FF CF FF CF FF CF FF D9 FF C6 FF BC FF C6 FF D9 FF D9 FF C6 FF C6 FF C6 FF C6 FF C6 FF BC FF B3 FF BC FF CF FF B3 FF B3 FF B3 FF C6 FF C6 FF BC FF BC FF C6 FF BC FF C6 FF BC FF BC FF BC FF B3 FF BC FF B3 FF B3 FF B3 FF BC FF BC FF B3 FF B3 FF B3 FF A9 FF B3 FF C6 FF 9F FF B3 FF C6 FF B3 FF A9 FF BC FF A9 FF BC FF B3 FF BC FF A9 FF A9 FF B3 FF B3 FF BC FF B3 FF BC FF ").mid(5);
//    Curve curve(dat, this);
//    curve.exec();
    if(time.isActive()) {
        this->ui->statusBar->showMessage(tr("正在测试测试电压值,请稍后再取曲线！"), 3000);
        return;
    }

    this->ui->statusBar->showMessage(tr("正在取曲线……"));
    char code[2];
    code[0] = 0x01;
    code[1] = 0xC2;
    socket.writeDatagram(code, 2, QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());
    qDebug() << "开起定时器……";
    time.start();
    ui->spinBox->setEnabled(false);
    ui->checkBox->setEnabled(false);
}

void TH_IAT114_I::loadName()
{
    QFileInfo file("DataName.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("DataName.ini", QSettings::IniFormat);
        read->setIniCodec("GBK");
        read->beginGroup("TH-IAT114-I");
        foreach(QString item, read->childKeys()) {
            this->name.insert(item.toInt(), read->value(item).toString());
        }
//        qDebug() << this->name;
    } else {
        qDebug() << "DataName.ini配置文件不存在！";
    }
}

void TH_IAT114_I::setName(unsigned int arg)
{
    if(0 == arg) {
        ui->label->setText("");
    } else {
        if(this->name.contains(arg)) {
            ui->label->setText(this->name.value(arg));
        } else {
            ui->label->setText("");
        }
    }
}
